package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	. "web_api_gin/controller"
	"web_api_gin/core"
	"web_api_gin/dao"
	"web_api_gin/dto"
	"web_api_gin/entity"
	"web_api_gin/service"
)

var SysUserApi = SysUserController{}

type SysUserController struct {
}

//用户列表接口
func (c *SysUserController) Index(ctx *gin.Context) {
	//用户列表
	var searchParams *dto.SysUserGetListReq
	if err := ctx.ShouldBind(&searchParams); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	userList, total, err := dao.SysUser.GetPageList(ctx, searchParams)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	//角色列表
	roleList, _, err := dao.SysRole.GetList(ctx, &dto.SysRoleGetListReq{})
	roleTreeOriginList := ([]*dto.SysRoleTree)(nil)
	for _, role := range roleList {
		roleTreeOriginList = append(roleTreeOriginList, &dto.SysRoleTree{
			SysRole: *role,
		})
	}
	//转树结构数据
	roleTreeList := service.SysRole.BuildTree(roleTreeOriginList)

	Success(ctx, gin.H{
		"userList": userList,
		"total":    total,
		"pageNo":   searchParams.PageNo,
		"roleList": roleTreeList,
		"permData": ctx.Value("permData"),
	})
}

//保存用户数据
func (c *SysUserController) Save(ctx *gin.Context) {
	var form *entity.SysUsers
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	//如设置密码则存储加密密码
	if form.Password != "" {
		encryptPwd, err := service.SysUser.GetUserPassword(form.Password)
		if err != nil {
			ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
			return
		}
		form.Password = encryptPwd
	}
	//保存用户数据
	if err := dao.SysUser.SaveUser(ctx, form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{})
}

//禁用用户
func (c *SysUserController) Disable(ctx *gin.Context) {
	var form *dto.SysUserFormDestroy
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	err := dao.SysUser.DisableUser(ctx, form.UserIds)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{})
}

//激活用户
func (c *SysUserController) Enable(ctx *gin.Context) {
	var form *dto.SysUserFormDestroy
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	err := dao.SysUser.EnableUser(ctx, form.UserIds)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusBadRequest, err.Error())
		return
	}
	Success(ctx, gin.H{})
}
